import React, { Component } from 'react';
import axios from 'axios';
import CommitItemUi from './CommitItemUi'
import store from './store'
import {setAddList , getInputValue , setDelItem ,getList} from './store/actionCreator'

class Commit extends Component{
    
    constructor(props){
        super(props)

        this.state = store.getState()
     
        this.addItem = this.addItem.bind(this)
        this.changeInput = this.changeInput.bind(this)
        this.storeChange = this.storeChange.bind(this)
        this.delItem = this.delItem.bind(this)
        

        store.subscribe(this.storeChange)

    };
    componentDidMount(){
        axios('http://rap2api.taobao.org/app/mock/292931/index').then(res=>{
            const action = getList(res.data.list)
            store.dispatch(action)
        })
    }
    render(){
        return(
            <CommitItemUi
                list={this.state.list}
                inputValue = {this.state.inputValue}
                addItem = {this.addItem}
                changeInput = {this.changeInput}
                delItem = {this.delItem}
            />
        )
    }

    //redux 订阅模式
    storeChange(){
        this.setState(store.getState())
    }

    addItem(){
        const action = setAddList()
        store.dispatch(action)
        // this.setState({
        //     list:[...this.state.list,this.state.inputValue]
        // })
    }

    changeInput(e){
        const action = getInputValue(e.target.value)
        store.dispatch(action)
    }

    delItem(index){
        console.log(index)
        const action = setDelItem(index)
        store.dispatch(action)
        // let list = this.state.list
        // list.splice(index,1)
        // this.setState({
        //     list:list
        // })
    }
}

export default Commit;